﻿using DDBS_Server.Models;
using Raven.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace DDBS_Server.ViewControllers
{
    [Authorize]
    public class DatabasesController : Controller
    {
        // GET: Databases
        public ActionResult Index()
        {
            using (IDocumentSession session = RavenContext.CreateSession())
            {
                List<Shard> results = new List<Shard>();
                try
                {
                    results = session.Query<Shard>().ToList();
                    ViewBag.shards = results;
                }
                catch(Exception e)
                {
                    ViewBag.Error = "Cannot load databases.";
                    ViewBag.ErrorDetail = e.ToString();
                }
            }
            return View();
        }

        // POST: Databases/Add
        [HttpPost]
        public ActionResult Add(FormCollection collection)
        {
            try
            {
                Shard shard = new Shard();
                shard.Name = collection["dbName"];
                shard.Identifier = collection["dbIdentifier"];
                shard.URL = collection["dbURL"];
                shard.DB = collection["dbShard"];

                using (IDocumentSession session = RavenContext.CreateSession())
                {
                    session.Store(shard);
                    session.SaveChanges();
                }
                Task.Delay(1000);
                return RedirectToAction("Index");
            }
            catch
            {
                return RedirectToAction("Index");
            }
        }

        // GET: Databases/Details/5
        public ActionResult Details(int id)
        {
            return View();
        }

        // GET: Databases/Edit/5
        public ActionResult Edit(int id)
        {
            return View();
        }

        // POST: Databases/Edit/5
        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: Databases/Delete/5
        public ActionResult Delete(int id)
        {
            return View();
        }
    }
}
